﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Ninject;
using Ninject.Modules;
using Intergaces;
using DomainModel;
using System.Reflection;
using System.Configuration;
using System.IO;


namespace ImageControlUI
{
    public partial class _default : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {


        }





        protected void Unnamed1_Click(object sender, EventArgs e)
        {
            //valid type
            if (FileUploadImage.PostedFile.ContentType == "image/jpeg" && FileUploadImage.PostedFile.ContentLength != 0)
            {
                ImageService imageService = GetImageService();


                var image = new ImageEntity();


                Stream streamOfImage = FileUploadImage.PostedFile.InputStream;

                //fill field of image class
                image.Id = Guid.NewGuid();
                image.DataFull = imageService.SetImageSize(streamOfImage, 400);
                image.DataSmall = imageService.SetImageSize(streamOfImage, 150);

                //save image in db
                imageService.SaveImage(image);

            }

        }

        protected ImageService GetImageService()
        {
            try
            {
                IKernel r = new StandardKernel();
                //get name reporitory from web.config
                string nameRepository = ConfigurationManager.AppSettings["Repository"];

                //load assembly
                Assembly assembly = LoadRepository(nameRepository);
                r.Load(assembly);


                //creat instance
                return new ImageService(r.Get<SqlRepository.SqlRepository>());
            }
            catch (Exception e)
            {
                //log
                throw new Exception("Can not creat instance", e);
            }
        }


        private Assembly LoadRepository(string nameRepository)
        {
            Assembly assembly = null;

            try
            {
                assembly = Assembly.Load(nameRepository);
            }
            catch (Exception ex)
            {
                //log
                throw new Exception("Can not load repository", ex);
            }
            return assembly;
        }

    }
}